﻿//------------------------------------------------------------------------------
// System Name:    Customer Service Platform
// Component:      Add new customers in CCS OCR
// Modify By:      Leo Ren (leoren@wicresoft.com)
// Modify Date:    2011-1-28
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using BEGDC.CC.BL.CCFlow.CR;
using BEGDC.CC.BL.Common;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using BEGDC.Utility.Castle;
using ASBCC.Business;
using ASBCC.Business.CIS;

namespace BEGDC.CC.Web.Common
{
    /// <summary>
    /// Summary description for CustomerInput.
    /// </summary>
    public class CustomerInputForOCV : System.Web.UI.Page
    {
        #region Variables
        protected System.Web.UI.WebControls.TextBox tbCustomerName;
        protected System.Web.UI.WebControls.TextBox tbCompany;
        protected System.Web.UI.WebControls.TextBox tbTitle;
        protected System.Web.UI.WebControls.Button Btn_Save;
        protected System.Web.UI.WebControls.Button Btn_Close;
        protected System.Web.UI.WebControls.TextBox tbRemark;
        protected System.Web.UI.WebControls.TextBox tbIsExist;
        protected System.Web.UI.WebControls.TextBox tbReturnValue;
        protected System.Web.UI.WebControls.TextBox tbMyCustomers;
        protected System.Web.UI.WebControls.DropDownList ddlAffects;
        protected System.Web.UI.WebControls.DropDownList ddlResponsibility;
        //Search
        protected System.Web.UI.WebControls.Button ibtnSearch;
        protected System.Web.UI.WebControls.TextBox tbSearchName;
        protected System.Web.UI.WebControls.TextBox tbSearchTitle;
        protected System.Web.UI.WebControls.TextBox tbSearchCompany;
        protected System.Web.UI.WebControls.ImageButton btnPageLast;
        protected System.Web.UI.WebControls.ImageButton btnPageNext;
        protected System.Web.UI.WebControls.ImageButton btnPagePrev;
        protected System.Web.UI.WebControls.ImageButton btnPageFirst;
        protected System.Web.UI.WebControls.DataGrid DG_CustomerList;
        protected System.Web.UI.WebControls.RadioButtonList rbEntertainmentNeed;
        protected System.Web.UI.WebControls.RadioButtonList rbGiftNeed;
        //protected System.Web.UI.WebControls.Label lbSalesCustomer;
        //protected System.Web.UI.WebControls.TextBox tbSalesCustomerExplain;
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            string CustomerAttendeeStr = Request["CustomerAttendeeId"];

            if (CustomerAttendeeStr != null)
            {
                this.RowID = Convert.ToInt32(CustomerAttendeeStr);
            }
            else
            {
                this.RowID = 0;
            }

            if (!this.IsPostBack)
            {
                //				this.Btn_Save.Attributes["onclick"] = "javascript:OnSave();";
                this.Btn_Close.Attributes["onclick"] = "javascript:OnClose();";
                //this.Btn_Save.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/bbw_OK.gif";
                //this.Btn_Close.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/bbw_close.gif";
                
                this.tbCustomerName.Attributes.Add("readonly", "true");
                this.tbCompany.Attributes.Add("readonly", "true");

                BindDropDownList();

                if (this.RowID > 0)
                {
                    InitForm();
                }
                else
                {
                    InitCustomerList(1);
                }
                //else
                //{
                //    InitFormFromSession();
                //}
                this.GetMyCustomers();
            }

            //if(this.tbReturnValue.Text != string.Empty)
            //{
            //    this.tbReturnValue.Text = WebUtility.DeCodeString(Server, this.tbReturnValue.Text);
            //    string[] temp = this.tbReturnValue.Text.Split('|');
            //    this.tbCustomerName.Text = temp[0];
            //    this.tbCompany.Text = temp[2];
            //    this.tbTitle.Text = temp[1];
            //    this.tbIsExist.Text = "1";

            //    this.tbReturnValue.Text = string.Empty;
            //}

        }

        private void BindDropDownList()
        {
            WebUtility.BuildDropDown(ddlResponsibility, BEGDC.CC.BL.Common.DicType.RESPONSIBILITY, false, false);
            WebUtility.BuildDropDown(ddlAffects, BEGDC.CC.BL.Common.DicType.AFFECTS, false, false);
        }

        #region RowID
        protected int RowID
        {
            get { return (int)this.ViewState["AttendeeID"]; }
            set { this.ViewState["AttendeeID"] = value; }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            DataTable contractInfo = null;
            DataRow row = null;
            object sessContractInfo = Session[SessionFlag.CustomerSessionEZ];
            if (sessContractInfo != null)
            {
                InitCustomerList(1);
                contractInfo = (DataTable)sessContractInfo;
            }
            else
            {
                InitCustomerList(1);
                return;
            }

            if (this.RowID > 0)
            {
                row = contractInfo.Rows[this.RowID - 1];

                this.tbCustomerName.Text = row["Name"].ToString();
                this.tbTitle.Text = row["TitleEN"].ToString();
                this.tbCompany.Text = row["CompanyEN"].ToString();

                this.ddlAffects.SelectedValue = row["AffectsID"].ToString();
                this.ddlResponsibility.SelectedValue = row["ResponsibilityID"].ToString();
                this.tbRemark.Text = row["Remark"].ToString();
                this.tbIsExist.Text = row["IsExisted"].ToString();

                this.rbEntertainmentNeed.SelectedValue = row["IsNeedEntertainment"].ToString();
                this.rbGiftNeed.SelectedValue = row["IsNeedGift"].ToString();
            }
        }
        #endregion

        //private void InitFormFromSession()
        //{
        //    DataTable contractInfo = null;
        //    DataRow row = null;
        //    object sessContractInfo = Session[SessionFlag.CustomerSessionEZ];
        //    if(sessContractInfo!=null)
        //    {
        //        contractInfo = (DataTable)sessContractInfo;
        //    }
        //    else
        //    {
        //        return;
        //    }

        //    if(contractInfo.Rows.Count > 0)
        //    {
        //        row = contractInfo.Rows[contractInfo.Rows.Count-1];
        //        this.tbCustomerName.Text = row["Name"].ToString();
        //        this.tbTitle.Text = row["TitleEN"].ToString();
        //        this.tbCompany.Text = row["CompanyEN"].ToString();

        //        this.ddlAffects.SelectedValue = row["AffectsID"].ToString();
        //        this.ddlResponsibility.SelectedValue = row["ResponsibilityID"].ToString();	
        //    }
        //}

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Save.Click += new EventHandler(Btn_Save_Click);
            this.ibtnSearch.Click += new EventHandler(SearchBtn_Click);
            this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
            this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
            this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
            this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
            this.DG_CustomerList.ItemDataBound += new DataGridItemEventHandler(DG_CustomerList_ItemDataBound);
            this.DG_CustomerList.PageIndexChanged += new DataGridPageChangedEventHandler(DG_CustomerList_PageIndexChanged);
            this.Btn_Close.Click += new EventHandler(Btn_Close_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion

        #region Update Customer Session
        private void UpdateCustomerSession(out bool isExisted)
        {
            isExisted = false;
            DataTable CustomerDataTable = null;
            DataRow CustomerRow = null;

            object SessCustomerAttendee = Session[SessionFlag.CustomerSessionEZ];
            if (SessCustomerAttendee != null)
            {
                CustomerDataTable = (DataTable)SessCustomerAttendee;
            }
            else
            {
                Response.Write("<script>alert('The session is missed, please reopen the application!!')</script>");
                return;
            }

            //add column
            if (!CustomerDataTable.Columns.Contains("AttendeeCount"))
                CustomerDataTable.Columns.Add("AttendeeCount", typeof(int));
            //add 送礼 column 
            if (!CustomerDataTable.Columns.Contains("IsNeedGift"))
                CustomerDataTable.Columns.Add("IsNeedGift", typeof(int));
            //add 娱乐 column 
            if (!CustomerDataTable.Columns.Contains("IsNeedEntertainment"))
                CustomerDataTable.Columns.Add("IsNeedEntertainment", typeof(int));

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            bool IsCustomerExisted = QueryService.IsExistedCustomer(this.tbCompany.Text, this.tbCustomerName.Text, this.tbTitle.Text);
            if (IsCustomerExisted)
                this.tbIsExist.Text = BEGDC.CC.BL.Common.CISFlag.Existed;
            else
                this.tbIsExist.Text = BEGDC.CC.BL.Common.CISFlag.NotExisted;

            if (this.RowID == 0)
            {
                if (CustomerDataTable.Select("Name='" + this.tbCustomerName.Text.Trim().Replace("'", "''") + "' And CompanyEN='" + this.tbCompany.Text.Trim().Replace("'", "''") + "' And TitleEN='" + this.tbTitle.Text.Trim().Replace("'", "''") + "'").Length > 0)
                {
                    isExisted = true;
                    Response.Write("<script>alert('This person is already in the list!')</script>");
                    return;
                }
                CustomerRow = CustomerDataTable.NewRow();

                int count = CustomerDataTable.Rows.Count + 1;
                CustomerRow["Id"] = count.ToString();
                CustomerRow["Name"] = this.tbCustomerName.Text.Trim();
                CustomerRow["CompanyEN"] = this.tbCompany.Text.Trim();
                CustomerRow["TitleEN"] = this.tbTitle.Text.Trim();
                CustomerRow["ResponsibilityID"] = this.ddlResponsibility.SelectedValue;
                CustomerRow["AffectsID"] = this.ddlAffects.SelectedValue;
                CustomerRow["Responsibility"] = this.ddlResponsibility.SelectedItem.Text;
                CustomerRow["Affects"] = this.ddlAffects.SelectedItem.Text;
                CustomerRow["Remark"] = this.tbRemark.Text;

                ////送礼次数
                //int giftCount = QueryService.GetGiftCount(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                ////娱乐次数
                //int entertainmentCount = QueryService.GetEntertainmentCount(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                //if (giftCount > 3 || entertainmentCount > 5)
                //{
                //    CustomerRow["IsExisted"] = "2";
                //}
                //else
                //{
                CustomerRow["IsExisted"] = this.tbIsExist.Text;
                //}
                CustomerRow["AttendeeCount"] = QueryService.GetCustomerAttendeeCountForOversea(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                CustomerRow["IsNeedGift"] = this.rbGiftNeed.SelectedValue;
                CustomerRow["IsNeedEntertainment"] = this.rbEntertainmentNeed.SelectedValue; ;

                CustomerDataTable.Rows.Add(CustomerRow);
            }
            else if (this.RowID > 0)
            {
                CustomerRow = CustomerDataTable.Rows[this.RowID - 1];

                CustomerRow["Name"] = this.tbCustomerName.Text;
                CustomerRow["TitleEN"] = this.tbTitle.Text;
                CustomerRow["CompanyEN"] = this.tbCompany.Text;
                CustomerRow["ResponsibilityID"] = this.ddlResponsibility.SelectedValue;
                CustomerRow["AffectsID"] = this.ddlAffects.SelectedValue;
                CustomerRow["Responsibility"] = this.ddlResponsibility.SelectedItem.Text;
                CustomerRow["Affects"] = this.ddlAffects.SelectedItem.Text;
                CustomerRow["Remark"] = this.tbRemark.Text;
                CustomerRow["IsExisted"] = this.tbIsExist.Text;

                ////送礼次数
                //int giftCount = QueryService.GetGiftCount(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                ////娱乐次数
                //int entertainmentCount = QueryService.GetEntertainmentCount(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                //if (giftCount > 3 || entertainmentCount > 5)
                //{
                //    CustomerRow["IsExisted"] = "2";
                //}
                //else
                //{
                CustomerRow["IsExisted"] = this.tbIsExist.Text;
                //}

                CustomerRow["AttendeeCount"] = QueryService.GetCustomerAttendeeCountForOversea(this.tbCustomerName.Text.Trim(), this.tbCompany.Text.Trim());
                CustomerRow["IsNeedGift"] = this.rbGiftNeed.SelectedValue;
                CustomerRow["IsNeedEntertainment"] = this.rbEntertainmentNeed.SelectedValue;
            }
            else
            {
                return;
            }

            Session[SessionFlag.CustomerSessionEZ] = SetRowID(CustomerDataTable);
        }
        #endregion

        #region Save
        void Btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                bool isExisted = false;
                UpdateCustomerSession(out isExisted);
                if (!isExisted)
                {
                    Response.Write("<script>window.close();window.returnValue='reload';</script>");
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
            //Response.Write("<script>window.close();window.returnValue='reload';</script>");
        }
        #endregion

        private DataTable SetRowID(DataTable table)
        {
            if (table != null && table.Rows.Count > 0)
                for (int i = 1; i <= table.Rows.Count; i++)
                {
                    table.Rows[i - 1][0] = i.ToString();
                }
            return table;
        }

        void Btn_Close_Click(object sender, EventArgs e)
        {
            Response.Write("<script>window.close();window.returnValue='close';</script>");
        }

        #region Search

        void SearchBtn_Click(object sender, EventArgs e)
        {
            if (this.tbSearchName.Text == "" && this.tbSearchTitle.Text == "" && this.tbSearchCompany.Text == "")
            {
                Page.RegisterClientScriptBlock("", "<script>alert('Please specify information about the customer');</script>");
                return;
            }
            else
            {
                //this.btnPageFirst.Visible = true;
                //this.btnPageLast.Visible = true;
                //this.btnPageNext.Visible = true;
                //this.btnPagePrev.Visible = true;
                InitForm(1);
            }
        }

        private void InitCustomerList(int pageIndex)
        {
            //this.btnPageFirst.Visible = true;
            //this.btnPageLast.Visible = true;
            //this.btnPageNext.Visible = true;
            //this.btnPagePrev.Visible = true;

            //bool IsDomestic = true;
            //bool IsDomestic = false;

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable CISSource = QueryService.GetOverseasCustomerFromCIS(string.Empty, string.Empty, string.Empty);

            int count = CISSource.DefaultView.Count;
            this.DG_CustomerList.DataSource = CISSource.DefaultView;
            this.DG_CustomerList.DataBind();

            SetPageCount(count, pageIndex);
        }

        private void InitForm(int pageIndex)
        {
            string CISName = this.tbSearchName.Text;
            string CISTitle = this.tbSearchTitle.Text;
            string CISCompany = this.tbSearchCompany.Text;
            //bool IsDomestic = true;
            //bool IsDomestic = false;

            IQuery QueryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            DataTable CISSource = QueryService.GetOverseasCustomerFromCIS(CISName, CISTitle, CISCompany);

            int count = CISSource.DefaultView.Count;
            this.DG_CustomerList.DataSource = CISSource.DefaultView;
            this.DG_CustomerList.DataBind();

            SetPageCount(count, pageIndex);
        }

        private void SetPageCount(int count, int pageIndex)
        {
            if (count > 0)
            {
                _RowCount = count;
                _PageCount = count / this.DG_CustomerList.PageSize;
                if (count % this.DG_CustomerList.PageSize > 0) _PageCount++;

                _CurrentPageIndex = pageIndex;
                SetPageNavi(pageIndex);
            }
            else
            {
                _RowCount = count;
                _PageCount = count;
                _CurrentPageIndex = 0;
                SetPageNavi(0);
            }
        }

        #endregion

        #region page navigation
        private int _PageCount
        {
            get
            {
                if (ViewState["PageCount"] != null) return (int)ViewState["PageCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }
        private int _CurrentPageIndex
        {
            get
            {
                if (ViewState["CurrentPageIndex"] != null) return (int)ViewState["CurrentPageIndex"];
                else
                    return 0;
            }
            set
            {
                ViewState["CurrentPageIndex"] = value;
            }
        }
        private int _RowCount
        {
            get
            {
                if (ViewState["RowCount"] != null) return (int)ViewState["RowCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["RowCount"] = value;
            }
        }

        private void SetPageNavi(int newPage)
        {
            if (newPage <= 1)
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first_inact.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre_inact.gif";
                this.btnPageFirst.Attributes["disabled"] = "true";
                this.btnPagePrev.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre.gif";
                this.btnPageFirst.Attributes.Remove("disabled");
                this.btnPagePrev.Attributes.Remove("disabled");
            }

            if (newPage >= _PageCount)
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next_inact.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last_inact.gif";
                this.btnPageNext.Attributes["disabled"] = "true";
                this.btnPageLast.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last.gif";
                this.btnPageNext.Attributes.Remove("disabled");
                this.btnPageLast.Attributes.Remove("disabled");
            }
        }

        #endregion

        #region CustomerList_PageIndexChanged

        void DG_CustomerList_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            try
            {
                //SetCheckedProjectList();
                this.DG_CustomerList.CurrentPageIndex = e.NewPageIndex;
                this.InitForm(e.NewPageIndex);
            }
            catch
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        #endregion

        #region ---------- paging events ----------------
        private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.DG_CustomerList.CurrentPageIndex = 0;
            this.InitForm(1);
        }

        private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == 1) return;
            this.DG_CustomerList.CurrentPageIndex = _CurrentPageIndex - 2;
            this.InitForm(_CurrentPageIndex - 1);
        }

        private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == _PageCount) return;
            this.DG_CustomerList.CurrentPageIndex = _CurrentPageIndex;
            this.InitForm(_CurrentPageIndex + 1);
        }

        private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.DG_CustomerList.CurrentPageIndex = _PageCount - 1;
            this.InitForm(_PageCount);
        }
        #endregion

        void DG_CustomerList_ItemDataBound(object sender, DataGridItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Attributes.Add("onclick ", "test(this); ");
                e.Item.ID = "ItemID ";
                e.Item.Cells[1].Text = e.Item.Cells[1].Text.Replace(" ", "&nbsp;");
                e.Item.Cells[3].Text = e.Item.Cells[3].Text.Replace(" ", "&nbsp;");
            }
        }

        private void GetMyCustomers()
        {
            var roles = (this.User as CSPrincipal).Role2s;
            string allrole = "";
            if (roles != null && roles.Length != 0)
            {
                foreach (var role in roles)
                {
                    allrole += role;
                    allrole += ",";
                }
                allrole = allrole.Substring(0, allrole.Length - 2);
            }
            this.tbMyCustomers.Text = "," + CustomerManageHelper.GetCustomerIDbyRoleID(allrole) + ",";
        }
    }
}
